import { StorageKeyEnum, TabPaneTypeEnum } from '../utils/enums';

const storage = localStorage;

function getMaxId(list: { id?: number; [key: string]: any }[]) {
  return Math.max(...list.map(({ id }: any) => id || 0));
}

// 保存项目列表
export function saveProjectList(list: ProjectItem[] = []) {
  return storage.setItem(StorageKeyEnum.PROJECT_LIST, JSON.stringify(list));
}
// 新增项目
export function insertProject(proItem: ProjectItem) {
  return new Promise(async (resolve, reject) => {
    try {
      const project = JSON.parse(JSON.stringify(proItem));
      const projectList = getProjectList();
      const proNameMap = projectList.reduce((p, c) => {
        p.set(c.name, 1);
        return p;
      }, new Map());
      const proCodeMap = projectList.reduce((p, c) => {
        p.set(c.code, 1);
        return p;
      }, new Map());
      const { name, code } = project;
      let errMsg;
      if (proNameMap.has(name)) {
        errMsg = `项目名称 ${name} 重复`;
      } else if (proCodeMap.has(code)) {
        errMsg = `项目编码 ${code} 重复`;
      }
      if (errMsg) {
        throw new Error(errMsg);
      }
      let maxId = 0;
      if (projectList.length) {
        maxId = getMaxId(projectList);
      }
      project.id = maxId + 1;
      project.createTime = Date.now();
      project.updateTime = Date.now();
      projectList.push(project);
      saveProjectList(projectList);
      resolve(true);
    } catch (e) {
      reject(e);
    }
  });
}

// 更新项目
export function updateProjectById(proItem: ProjectItem) {
  return new Promise((resolve, reject) => {
    try {
      const project = JSON.parse(JSON.stringify(proItem));
      delete project.commandTerminals;
      const projectList = getProjectList();
      const { name, code, id } = project;
      let errMsg;
      if (projectList.some((pro) => pro.name === name && pro.id !== id)) {
        errMsg = '项目名称重复';
      } else if (
        projectList.some((pro) => pro.code === code && pro.id !== id)
      ) {
        errMsg = '项目编码重复';
      }
      if (errMsg) {
        throw new Error(errMsg);
      }
      project.updateTime = Date.now();
      const index = projectList.findIndex(({ id }) => id === project.id);
      if (index > -1) {
        projectList.splice(index, 1, project);
        saveProjectList(projectList);
        resolve(proItem);
      } else {
        throw new Error('没有找到目标项目');
      }
    } catch (e) {
      reject(e);
    }
  });
}

// 删除项目
export function delProjectById(id: number) {
  return new Promise((resolve, reject) => {
    try {
      const projectList = getProjectList();
      const index = projectList.findIndex(({ id: pid }) => pid === id);
      if (index > -1) {
        projectList.splice(index, 1);
        saveProjectList(projectList);
        resolve(true);
      } else {
        throw new Error('没有找到目标项目');
      }
    } catch (e) {
      reject(e);
    }
  });
}

export function queryProjects(cateId?: number, keyword?: string) {
  return new Promise((resolve, reject) => {
    try {
      const allList = getProjectList();
      let list = allList
        .filter((item) => {
          const { cateId: itemCateId } = item;
          return !cateId || cateId === itemCateId;
        })
        .map((item) => ({
          ...item,
          tagName: item.name,
          tagCode: item.code,
          tagDescription: item.description,
        }));
      if (keyword) {
        const reg = new RegExp(keyword, 'ig');
        list = list
          .filter((item) => {
            const { name, code, description } = item;
            return (
              (name && reg.test(name)) ||
              (code && reg.test(code)) ||
              (description && reg.test(description))
            );
          })
          .map((item) => {
            const { name, code, description } = item;
            return {
              ...item,
              tagName: name?.replaceAll(reg, (k) => `<b class="red">${k}</b>`),
              tagCode: code?.replaceAll(reg, (k) => `<b class="red">${k}</b>`),
              tagDescription: description?.replaceAll(
                reg,
                (k) => `<b class="red">${k}</b>`,
              ),
            };
          });
      }

      resolve({
        list,
        total: list.length,
      });
    } catch (e) {
      reject(e);
    }
  });
}

export function saveProjects(list: ProjectItem[] = []) {
  return new Promise((resolve, reject) => {
    try {
      saveProjectList(list);
      resolve(true);
    } catch (e) {
      reject(e);
    }
  });
}

// 获取项目列表
export function getProjectList(): ProjectItem[] {
  const projectList: ProjectItem[] = JSON.parse(
    storage.getItem(StorageKeyEnum.PROJECT_LIST) || '[]',
  );
  return projectList.sort((a, b) => (b.updateTime || 0) - (a.updateTime || 0));
}

// 保存tab数据
const listPaneData: TabPaneData = {
  title: '项目列表',
  closeable: false,
  code: 'list',
  type: TabPaneTypeEnum.LIST,
};

const defaultPaneList: TabPaneData[] = [];

export function saveTabPaneList(panes?: TabPaneData[]) {
  storage.setItem(StorageKeyEnum.TAB_PANE_LIST, JSON.stringify(panes));
}

export function getTabPaneList(): TabPaneData[] {
  const tabPaneList: TabPaneData[] =
    JSON.parse(storage.getItem(StorageKeyEnum.TAB_PANE_LIST) || '[]') ||
    defaultPaneList;

  return Array.isArray(tabPaneList) ? tabPaneList : defaultPaneList;
}

// 新增tabPane
export function insertTabPane(paneItem: TabPaneData) {
  return new Promise((resolve, reject) => {
    try {
      const pane = JSON.parse(JSON.stringify(paneItem));
      const paneList = getTabPaneList();
      const index = paneList.findIndex(({ code }) => code === pane.code);
      if (index > -1) {
        const paneItem = paneList[index];
        const { data: paneData } = pane;
        const { data: paneItemData } = paneItem;
        const newPane = {
          ...paneItem,
          ...pane,
          data: {
            ...paneItemData,
            ...paneData,
          },
        };
        paneList.splice(index, 1, newPane);
      } else {
        paneList.push(pane);
      }
      saveTabPaneList(paneList);
      resolve(true);
    } catch (e) {
      reject(e);
    }
  });
}
// 更新tabPane
export function updateTabPaneByCode(paneItem: TabPaneData) {
  return new Promise((resolve, reject) => {
    try {
      const pane = JSON.parse(JSON.stringify(paneItem));
      const paneList = getTabPaneList();
      const index = paneList.findIndex(({ code }) => code === pane.code);
      if (index > -1) {
        paneList.splice(index, 1, pane);
        saveTabPaneList(paneList);
        resolve(true);
      } else {
        throw new Error('没有找到目标项目');
      }
    } catch (e) {
      reject(e);
    }
  });
}

// 删除tabPane
export function delTabPaneByCode(code: string) {
  return new Promise((resolve, reject) => {
    try {
      const paneList = getTabPaneList();
      const index = paneList.findIndex(({ code: pCode }) => pCode === code);
      if (index > -1) {
        paneList.splice(index, 1);
        saveTabPaneList(paneList);
        resolve(true);
      } else {
        throw new Error('没有找到目标项目');
      }
    } catch (e) {
      reject(e);
    }
  });
}

export function queryTabPanes() {
  return new Promise((resolve, reject) => {
    try {
      resolve(getTabPaneList());
    } catch (e) {
      reject(e);
    }
  });
}

export function saveTabPanes(list: TabPaneData[] = []) {
  return new Promise((resolve, reject) => {
    try {
      saveTabPaneList(list);
      resolve(true);
    } catch (e) {
      reject(e);
    }
  });
}
// 清空
export function clearTabPanes() {
  return saveTabPanes([]);
}

// 获取所有分类
export function saveCateList(cateList?: CateItem[]) {
  storage.setItem(StorageKeyEnum.CATE_LIST, JSON.stringify(cateList));
}

export function getCateList() {
  const cateList: CateItem[] =
    JSON.parse(storage.getItem(StorageKeyEnum.CATE_LIST) || '[]') || [];
  return cateList;
}

export function queryCateList() {
  return new Promise((resolve) => {
    const cateList = getCateList();
    resolve(cateList);
  });
}

// 新增分类
export function addCate(cate: CateItem) {
  return new Promise((resolve) => {
    const cateList = getCateList();
    if (cateList.find((item) => item.name === cate.name)) {
      throw new Error('分类名称重复');
    }
    const maxId =
      cateList.length > 0 ? Math.max(...cateList.map((item) => item.id)) : 0;
    cate.id = maxId + 1;
    saveCateList([...cateList, cate]);
    resolve(1);
  });
}

// 修改分类名称
export function updateCate(cate: CateItem) {
  return new Promise((resolve, reject) => {
    const cateList = getCateList();
    if (
      cateList.find((item) => item.name === cate.name && cate.id !== item.id)
    ) {
      throw new Error('分类名称重复');
    }
    const index = cateList.findIndex((item) => item.id === cate.id);
    if (index === -1) {
      throw new Error('未找到分类');
    }
    cateList.splice(index, 1, cate);
    saveCateList(cateList);
    resolve(1);
  });
}
// 删除
export function removeCate(cateId: number) {
  return new Promise((resolve) => {
    const cateList = getCateList();
    const index = cateList.findIndex((item) => item.id === cateId);
    if (index === -1) {
      throw new Error('未找到分类');
    }
    cateList.splice(index, 1);
    saveCateList(cateList);
    resolve(1);
  });
}
